package com.b2b2c.until;

import java.util.HashMap;
import java.util.Map;

public class DataParse<T> implements DataParseInterface {

	private T data;


	@SuppressWarnings("rawtypes")
	private static volatile DataParse instance;
	
	private static Map<String, String> mapper = new HashMap<String, String>();
	
	/**
	 * 参数
	 */
	private Object [] args;
	
	private DataParse(T data) {
		this.setData(data);
		
	}
	
	public DataParse<?> setParam(Object ...objects)
	{
		this.args = objects;
		
		return this;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> DataParse<T> getInstance(T data) {

		if (instance == null) {

			synchronized (DataParse.class) {

				if (instance == null) {

					instance = new DataParse<T>(data);
					
					mapper.put("java.util.ArrayList", "com.b2b2c.until.parse.ArrayListParse");
					
					mapper.put("java.util.HashMap", "com.b2b2c.until.parse.HashMapParse");
					
				}

			}

		} else {
			instance.setData(data);
		}

		return  instance;

	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}
	

	@SuppressWarnings("unchecked")
	public <V> V getResult(String method, Class<?> ...objClassName) {
		// TODO Auto-generated method stub
		
		Class<? extends Object> dataClassName = this.data.getClass();
		
		Class<? extends Object>[] interfaceClass = dataClassName.getInterfaces();
		
		String t = dataClassName.getName();
		
		String className = mapper.get(t);
		
		V parseData = null;
		
		try {
			
			Class<?> parseClass = Class.forName(className);
			
			System.out.println(dataClassName);
			
			Object obj = parseClass.getConstructor(interfaceClass[0]).newInstance(data);
			
			parseData =  (V) parseClass.getDeclaredMethod(method, objClassName).invoke(obj, args);
			
			System.out.println(parseData);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return parseData;
	}

}
